import paho.mqtt.client as mqtt

class MqttCallback:
    """
    MQTT 回调接口，用于处理连接和消息事件
    """

    def on_connect(self, client, userdata, flags, rc):
        """
        当客户端连接到 MQTT Broker 时触发
        :param client: 客户端实例
        :param userdata: 用户数据
        :param flags: 连接标志
        :param rc: 返回码（0 表示成功）
        """
        pass

    def on_message(self, client, userdata, msg):
        """
        当客户端收到消息时触发
        :param client: 客户端实例
        :param userdata: 用户数据
        :param msg: 消息对象，包含 topic 和 payload 等信息
        """
        pass




class MqttUtil:
    def __init__(self, broker_address, broker_port=1883, client_id=None,  callback: MqttCallback = None):
        """
        初始化 MQTT 客户端
        :param broker_address: MQTT Broker 地址
        :param broker_port: MQTT Broker 端口
        :param client_id: 客户端 ID
        :param callback: 实现 MqttCallback 接口的对象
        """
        self.broker_address = broker_address
        self.broker_port = broker_port
        self.client = mqtt.Client(client_id=client_id) #  创建 MQTT 客户端实例
        self.callback = callback if callback else MqttCallback()


        self.client.on_connect = self.callback.on_connect #  设置连接回调
        self.client.on_message = self.callback.on_message #  设置消息接收回调

    #  连接
    def connect(self):
        """连接到 MQTT Broker"""
        self.client.connect(self.broker_address, self.broker_port)
        print("Connected to MQTT Broker")

    def on_connect(self, client, userdata, flags, rc):
        """连接回调"""
        if rc == 0:
            print("MQTT Client Connected")
        else:
            print(f"MQTT Client Connection Failed with code {rc}")

    def on_message(self, client, userdata, msg):
        """消息接收回调"""
        print(f"Received message: {msg.payload.decode()} on topic {msg.topic}")

    #  发布
    def publish(self, topic, message):
        """发布消息"""
        self.client.publish(topic, message)
        print(f"Published message to topic {topic}")

    # 订阅
    def subscribe(self, topic):
        """订阅主题"""
        self.client.subscribe(topic)
        print(f"Subscribed to topic {topic}")

    def loop_start(self):
        """开始循环（用于持续接收消息）"""
        self.client.loop_start()

    def loop_stop(self):
        """停止循环"""
        self.client.loop_stop()

    def disconnect(self):
        """断开连接"""
        self.client.disconnect()
        print("Disconnected from MQTT Broker")
